package boot.spring.service;

import boot.spring.config.WebSocketThread;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.DateUtils;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author 豆腐脑
 * @date 2023-2-20
 */
@Component
@Configuration
public class WebSocketClientConfig {

    @Value("${webs.ws}")
    private String ws;  // 第三方服务器的websocket接口

    @Value("${webs.httpUrl}")
    private String httpUrl; // http接口

    public static WebSocketClient client;

    // 是否连接
    public static boolean isConnect = false;

    // 单例线程池
    ExecutorService executorService = Executors.newSingleThreadExecutor();

    @Bean
    public WebSocketClient getWebSocketClient() {
        try {
            client = new WebSocketClient(new URI(ws), new Draft_6455()) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    System.out.println("握手成功！");
                    isConnect = true;
                }

                @Override
                public void onMessage(String msg) {
                    System.out.println("收到服务器端的消息：" + msg);
                    // 判断msg是否为空
                    if (null != msg && !msg.trim().equals("")) {
                        // 异步线程加入线程池，进行发送操作
                        executorService.execute(new WebSocketThread(httpUrl, msg));
                    }
                }

                @Override
                public void onError(Exception e) {
                    e.printStackTrace();
                    executorService.shutdown();
                    isConnect = false;
                    System.out.println("发生错误已关闭");
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    System.out.println("连接已关闭");
                    executorService.shutdown();
                    isConnect = false;
                }

                @Override
                public void onMessage(ByteBuffer bytes) {
                    try {
                        System.out.println(new String(bytes.array(), "utf-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            };
//            使用ScheduledExecutorService，延迟1秒后，第一次执行，然后每隔5秒检测一下是否断线，如果断线进行重连
            System.out.println("启动于：" + DateUtils.createNow());
            ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);
            executorService.scheduleWithFixedDelay(
                    new Runnable() {
                        int i = 1;

                        @Override
                        public void run() {
                            if (!isConnect) {
                                WebSocketClient client = getWebSocketClient();
                                System.out.println("正在连接中...");
                                if (client.getReadyState().equals(ReadyState.NOT_YET_CONNECTED)) {
                                    // 未连接状态
                                    try {
                                        client.connect();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                } else if (client.getReadyState().equals(ReadyState.CLOSING) || client.getReadyState().equals(ReadyState.CLOSED)) {
                                    // 正关闭状态 或者 关闭状态
                                    try {
                                        client.reconnect();
                                    } catch (IllegalArgumentException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    },
                    1, 5, TimeUnit.SECONDS);
//            Timer timer = new Timer();
//            timer.schedule(new TimerTask() {
//                @Override
//                public void run() {
//                    if (!isConnect) {
//                        WebSocketClient client = getWebSocketClient();
//                        System.out.println("正在连接中...");
//                        if (client.getReadyState().equals(ReadyState.NOT_YET_CONNECTED)) {
//                            // 未连接状态
//                            try {
//                                client.connect();
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        } else if (client.getReadyState().equals(ReadyState.CLOSING) || client.getReadyState().equals(ReadyState.CLOSED)) {
//                            // 正关闭状态 或者 关闭状态
//                            try {
//                                client.reconnect();
//                            } catch (IllegalArgumentException e) {
//                                e.printStackTrace();
//                            }
//                        }
//
//                    }
//                }
//            }, 1000, 5000);
            // client.connect();// 连接
            return client;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return null;
    }

}